package com.tgy.leetcode;



public class _61_旋转链表 {

    public static ListNode rotateRight(ListNode head, int k) {

        if (k == 0 || head == null || head.next == null) {
            return head;
        }

        int len = 0;
        ListNode node = head;
        while (node != null) {

            len++;
            node = node.next;
        }

        int count = k % len;

        if (count == 0) {

            return head;
        }

        ListNode preHead  = head, preTail = preHead, lastHead = null,lastTail = null;

        int split = len - count;
        int index = 0;
        node = head;
        while (node != null) {

            if (index < split) {

                preTail = node;
            }else if (index == split) {

                lastHead = node;
                lastTail = lastHead;
            }else  {

                lastTail = node;
            }

            index++;
            node = node.next;
        }

        lastTail.next = preHead;
        preTail.next = null;
        return lastHead;
    }
}
